const path = require('path')
const resolve = dir => path.join(__dirname, dir)
const { devServer } = require('./faceConfig')
const { WebpackWarPlugin } = require('webpack-war-plugin')
const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV)
const proxyConfig = {
  '/ces': {
    target: devServer,
    ws: true, // 是否启用websockets
    changeOrigin: true, // 开启代理，在本地创建一个虚拟服务端
    pathRewrite: {
      '^/ces': '/ces',
    },
  },
}
module.exports = {
  // 公共路径
  publicPath: './',
  // 输出文件目录
  outputDir: 'dist',
  // eslint-loader 是否在保存的时候检查
  lintOnSave: true,
  // 生产环境的不需要 source map
  productionSourceMap: false,
  css: {
    extract: IS_PROD,
    sourceMap: !IS_PROD,
    loaderOptions: {
      scss: {
        prependData: '@import "@/assets/scss/var.scss";', //引入全局变量
      },
    },
  },
  chainWebpack: config => {
    // 修复HMR
    config.resolve.symlinks(true)

    // 设置别名
    config.resolve.alias
      .set('@', resolve('./src'))
      .set('@assets', resolve('./src/assets'))
      .set('@scss', resolve('./src/assets/scss'))
      .set('@components', resolve('./src/components'))
      .set('@api', resolve('./src/api'))
      .set('@views', resolve('./src/views'))
      .set('@common', resolve('./src/views/common'))
      .set('@router', resolve('./src/router'))
      .set('@store', resolve('./src/store'))
    // .set('faceConfig', resolve('faceConfig.js'))

    // 设置构建 war 包
    if (IS_PROD) {
      config.plugin('war').use(WebpackWarPlugin, [{ archiveName: 'web-app' }])
    }
  },
  configureWebpack: config => {
    // config.mode = 'development'
    config.optimization = {
      splitChunks: {
        cacheGroups: {
          common: {
            name: 'chunk-common',
            chunks: 'all',
            minChunks: 2,
            maxInitialRequests: 10,
            maxAsyncRequests: 10,
            minSize: 0,
            priority: 20,
            reuseExistingChunk: true,
            enforce: true,
          },
          vendors: {
            name: 'chunk-vendors',
            test: /[\\/]node_modules[\\/]/,
            chunks: 'initial',
            priority: 0,
            reuseExistingChunk: true,
            enforce: true,
          },
          elementUI: {
            name: 'chunk-elementui-plus',
            test: /[\\/]node_modules[\\/]element-plus[\\/]/,
            chunks: 'all',
            priority: 10,
            reuseExistingChunk: true,
            enforce: true,
          },
          faceConfig: {
            name: 'chunk-faceConfig',
            // test(module) {
            //   return module.resource && module.resource.indexOf('faceConfig') >= 0
            // },
            test: /faceConfig/,
            chunks: 'all',
            priority: 30,
            reuseExistingChunk: true,
            enforce: true,
          },
        },
      },
    }
  },
  devServer: {
    compress: true,
    disableHostCheck: true,
    port: 4000,
    open: true,
    hot: true,
    proxy: proxyConfig,
  },
}
